package com.elock.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.elock.base.core.ExcelView;
import com.elock.base.core.Page;
import com.elock.base.core.Pageable;
import com.elock.base.core.controller.BaseController;
import com.elock.base.core.controller.ResultMsg;
import com.elock.base.core.util.JsonUtils;
import com.elock.base.core.util.WebUtils;
import com.elock.service.TerminalMessageEventService;
import com.elock.service.TerminalSaleOrgService;
import com.elock.service.TerminalService;
import com.elock.util.SystemConfig;

/**
 * Controller - 钥匙监控列表
 * @author 仁德
 */
@Controller("terminalMonitorController")
@RequestMapping("/terminal_monitor")
public class TerminalMonitorController extends BaseController {

	@Resource(name = "terminalServiceImpl")
	private TerminalService terminalService;
	@Resource(name = "terminalSaleOrgServiceImpl")
	private TerminalSaleOrgService terminalSaleOrgService;
	@Resource(name = "terminalMessageEventServiceImpl")
	private TerminalMessageEventService terminalMessageEventService;

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list_tb", method = RequestMethod.GET)
	public String list_tb(ModelMap model) {

		return "/terminal_monitor/list_tb";
	}

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Pageable pageable, ModelMap model) {

		return "/terminal_monitor/list";
	}

	/**
	 * 列表数据
	 */
	@RequestMapping(value = "/list_data", method = RequestMethod.POST)
	public @ResponseBody ResultMsg list_data(Integer type, Long saleOrgId,
			String terminalNum, String sim, String startTime, String endTime,
			Pageable pageable, ModelMap model) {
//		List<Filter> fis = new ArrayList<Filter>();
//		if (type == null || oid == null) {
//			fis.add(Filter.isNotNull("plateNum"));
//			Page<TerminalMessageEvent> page = terminalMessageEventService.findPage(fis,
//					null,
//					pageable);
//			String jsonPage = JsonUtils.toJson(page);
//			return success(jsonPage);
//		}
//
//		Page<Map<String, Object>> pageMap = terminalMessageEventService.findPage(type,
//				oid == 0 ? 99 : oid,
//				pageable);
//		String jsonPage = JsonUtils.toJson(pageMap);

		Page<Map<String, Object>> pageMap = terminalService.findTerminalMonitorPage(
				terminalNum, sim, saleOrgId, startTime, endTime, pageable);
		String jsonPage = JsonUtils.toJson(pageMap);

		return success(jsonPage);
	}

	@RequestMapping(value = "/to_condition_export", method = RequestMethod.POST)
	public @ResponseBody List<Map<String, Object>> toConditionExport(Integer type,
			Long saleOrgId, String terminalNum, String sim, String startTime,
			String endTime, Pageable pageable, ModelMap model) {

		Integer size = terminalService.countTerminalMonitor(terminalNum,
				sim,
				saleOrgId,
				startTime,
				endTime,
				pageable,
				null,
				null);
		List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
		Map<String, Integer> segments = getSegment();
		int stage = segments.get("segment");
		int page_size = segments.get("size");
		for (int i = 0; i < stage; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			int total = i * page_size;
			if (size == 0) {
				map.put("data", "0-0");
			}
			else if ((size - total) <= page_size) {
				map.put("data", (total + 1) + "-" + size);
			}
			else {
				map.put("data", (total + 1) + "-" + (i + 1) * page_size);
			}
			lists.add(map);
			if ((size - total) <= page_size) {
				break;
			}
		}
		return lists;
	}

	/**
	 * 条件导出
	 * @return
	 */
	@RequestMapping(value = "/condition_export", method = RequestMethod.GET)
	public ModelAndView conditionExport(Integer type, Long saleOrgId, String terminalNum,
			String sim, String startTime, String endTime, Pageable pageable,
			ModelMap model, Integer page) {

		Map<String, Integer> segments = getSegment();
		int size = segments.get("size");
		List<Map<String, Object>> data = terminalService.findTerminalMonitorList(
				terminalNum, sim, saleOrgId, startTime, endTime, pageable, page, size);
		return this.getModelAndView(data, model);

	}

	public ModelAndView getModelAndView(List<Map<String, Object>> data, ModelMap model) {
		for (Map<String, Object> str : data) {
			if (str.get("is_online") != null) {
				Integer is_online = (Integer) str.get("is_online");
				if (is_online == 0) {
					str.put("is_online_str", "离线");
				}
				else {
					str.put("is_online_str", "在线");
				}
			}
			if (str.get("vol") != null) {
				str.put("vol",
						new BigDecimal(str.get("vol").toString()).setScale(2,
								BigDecimal.ROUND_HALF_UP));
			}
			if (str.get("speed") != null) {
				str.put("speed",
						new BigDecimal(str.get("speed").toString()).setScale(2,
								BigDecimal.ROUND_HALF_UP));
			}
//			if (str.get("create_date") != null) {
//
//				String create_date = DateUtil.convert((Date) str.get("create_date"));
//				if (create_date.length() > 19) {
//					create_date = create_date.substring(0, 19);
//				}
//				str.put("create_date", create_date);
//			}
//			if (str.get("is_enabled") != null && (Boolean) str.get("is_enabled")) {
//				str.put("is_enabled", "是");
//			}
//			else {
//				str.put("is_enabled", "否");
//			}
		}

		//设置导出表格名
		String filename = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + ".xls";
		//设置标题
		String[] header = { "终端设备编号",
				"SIM卡号",
				"版本号",
				"是否在线",
				"上线时间",
				"状态信息描述",
				"电压",
				"经度",
				"纬度",
				"基站定位数据",
				"海拔高度",
				"速度",
				"方向",
				"GPS时间",
				"备注" };
		//设置单元格取值
		String[] properties = { "terminal_num",
				"sim",
				"version",
				"is_online_str",
				"online_time",
				"status_desc",
				"vol",
				"longitude",
				"latitude",
				"jzdw",
				"altitude",
				"speed",
				"direction",
				"gps_time",
				"remark" };

		return new ModelAndView(
				new ExcelView(filename, null, properties, header, null, null, data, null),
				model);
	}

	private Map<String, Integer> getSegment() {
		HashMap<String, Integer> map = new HashMap<String, Integer>();
		try {
			String value = SystemConfig.getConfig("SegmentExportConfig",
					WebUtils.getCurrentCompanyInfoId());
			String[] values = value.split(",");
			map.put("segment", Integer.parseInt(values[0]));
			map.put("size", Integer.parseInt(values[1]));
		}
		catch (Exception e) {
			map.put("segment", 10);
			map.put("size", 1000);
		}
		return map;
	}
}
